<template>
  <el-dialog v-model="dialogVisible" width="1200px">
    <el-skeleton :loading="loading" animated>
      <template #template>
        <el-skeleton-item variant="text" style="width: 100%" />
        <el-skeleton-item variant="text" style="width: 100%" />
        <el-skeleton-item variant="text" style="width: 60%" />
      </template>
      <template #default>

        <el-descriptions :column="3" border>
          <el-descriptions-item label="项目名称">
            {{ props.volumeData.protitle }}
          </el-descriptions-item>
          <el-descriptions-item label="案卷名称">
            {{ props.volumeData.title }}
          </el-descriptions-item>
          <el-descriptions-item label="案卷档号">
            {{ props.volumeData.archcode }}
          </el-descriptions-item>
          <el-descriptions-item label="互见号">
            {{ props.volumeData.relatecode }}
          </el-descriptions-item>
          <el-descriptions-item label="项目负责人">
            {{ props.volumeData.xmfzr }}
          </el-descriptions-item>
          <el-descriptions-item label="合同号">
            {{ props.volumeData.hth }}
          </el-descriptions-item>
        </el-descriptions>
        <!-- 添加表格和分页 -->
        <el-table :data="tableData" style="width: 100%; margin-top: 20px;">
          <el-table-column type="index" label="序号" width="60" :index="calculateIndex" />
          <el-table-column prop="title" label="文件名称" width="300" />
          <el-table-column prop="creatername" label="编制人" width="" />
          <el-table-column prop="docnumber" label="文件编号" width="180" />
          <el-table-column prop="tjztlx" label="文件格式" width="170" />
          <el-table-column prop="editor" label="项目负责人" width="140" />
          <el-table-column label="操作" width="220" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" link size="small" @click="handleViewFile(row)">
                查看
              </el-button>
              <template v-if="userStore.currentUser">
                <el-button type="primary" link size="small" @click="showUploadDialog(row)">
                  添加
                </el-button>
                <el-popconfirm
                  title="确认删除该文件吗？"
                  @confirm="handleDelete(row)"
                  @cancel="handleDeleteCancel"
                >
                  <template #reference>
                    <el-button type="danger" link size="small">删除</el-button>
                  </template>
                </el-popconfirm>
              </template>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination-container">
          <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :total="total"
            :page-sizes="[20, 50, 100, 200]" @size-change="handleSizeChange" @current-change="handleCurrentChange"
            layout="sizes, prev, pager, next, total" class="pagination" />
        </div>
      </template>
    </el-skeleton>
  </el-dialog>

  <!-- 添加文件详情弹窗 -->
  <FileDetailModal v-model:visible="fileModalVisible" :docid="docid" />

  <!-- 简化的上传文件弹框 -->
  <el-dialog v-model="uploadDialogVisible" title="添加文件" width="400px">
    <el-upload
      ref="uploadRef"
      :auto-upload="false"
      :limit="1"
      :on-change="handleFileChange"
      :on-exceed="handleExceed"
      :on-remove="handleRemove"
    >
      <el-button type="primary">选择文件</el-button>
    </el-upload>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancelUpload">取消</el-button>
        <el-button type="primary" @click="submitUpload" :disabled="!selectedFile">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch } from 'vue';
import request from '@/utils/request';
import { ElMessage, ElMessageBox } from 'element-plus';
import FileDetailModal from './FileDetailsModal.vue';
import { useUserStore } from '@/stores/userStore'

const userStore = useUserStore()

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  volumeId: {
    type: [String, Number],
    default: ''
  },
  volumeData: {
    type: Object,
    default: {}
  }
});

const emit = defineEmits(['update:visible']);

const dialogVisible = ref(props.visible);
const loading = ref(false);
const volumeData = ref({});
const tableData = ref([]);
const currentPage = ref(1);
const pageSize = ref(100);
const total = ref(0);

// 监听弹窗显示状态
watch(() => props.visible, (newValue) => {
  dialogVisible.value = newValue;
  if (newValue && props.volumeId) {
    fetchVolumeDetails(); // 获取文件列表
  }
});

watch(dialogVisible, (newValue) => {
  emit('update:visible', newValue);
  if (!newValue) {
    volumeData.value = {};
    tableData.value = [];
    currentPage.value = 1;
    total.value = 0;
  }
});

// 获取卷册详情数据
const fetchVolumeDetails = async () => {
  try {
    loading.value = true;
    const { data } = await request.post('/zhsj/api/getdocpagebyid', null, {
      params: {
        pageindex: currentPage.value,
        pagesize: pageSize.value,
        volid: props.volumeId
      }
    });

    if (data) {
      tableData.value = data.records || [];
      total.value = data.total || 0;
    } else {
      ElMessage.warning('未找到详细信息');
    }
  } catch (error) {
    console.error('Failed to load volume details:', error);
    ElMessage.error('获取详情失败');
  } finally {
    loading.value = false;
  }
};


// 计算序号
const calculateIndex = (index) => {
  return (currentPage.value - 1) * pageSize.value + index + 1;
};

// 处理页码变化
const handleCurrentChange = (page) => {
  currentPage.value = page;
  fetchVolumeDetails();
};

// 处理每页条数变化
const handleSizeChange = (size) => {
  pageSize.value = size;
  currentPage.value = 1;
  fetchVolumeDetails();
};

// 添加新的响应式变量
const fileModalVisible = ref(false);
const docid = ref(null);
const uploadDialogVisible = ref(false)
const uploadRef = ref(null)
const selectedFile = ref(null)
const currentDoc = ref(null)

// 修改查看文件处理函数
const handleViewFile = (row) => {
  docid.value = row.idstr;
  fileModalVisible.value = true;
};

// 修改显示上传对话框方法
const showUploadDialog = (row) => {
  currentDoc.value = row
  uploadDialogVisible.value = true
  selectedFile.value = null
  if (uploadRef.value) {
    uploadRef.value.clearFiles()
  }

}

// 文件选择变化处理
const handleFileChange = (file) => {
  selectedFile.value = file
}

// 移除文件
const handleRemove = () => {
  selectedFile.value = null
}

// 超出文件数量限制处理
const handleExceed = () => {
  ElMessage.warning('只能上传一个文件')
}

// 修改取消上传方法，重置文档ID
const cancelUpload = () => {
  uploadDialogVisible.value = false
  selectedFile.value = null
  currentDocId.value = null
  if (uploadRef.value) {
    uploadRef.value.clearFiles()
  }
}

// 修改提交上传方法，加入文档ID
const submitUpload = async () => {
  if (!selectedFile.value) {
    ElMessage.warning('请选择文件')
    return
  }

  try {
    loading.value = true
    const formData = new FormData()
    formData.append('file', selectedFile.value.raw)

    await request.post(`/zhsj/api/savefile/zhsj/${currentDoc.value.idstr}/${currentDoc.value.projectidstr}`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })

    ElMessage.success('上传成功')
    uploadDialogVisible.value = false
    selectedFile.value = null
    currentDoc.value = null
    fetchVolumeDetails() // 刷新列表
  } catch (error) {
    ElMessage.error('上传失败：' + error.message)
  } finally {
    loading.value = false
  }
}

// 处理删除
const handleDelete = async (row) => {
  try {
    loading.value = true
    await request.post(`/zhsj/api/delfile?id=${row.id}`)
    ElMessage.success('删除成功')
    fetchVolumeDetails() // 刷新列表
  } catch (error) {
    ElMessage.error('删除失败：' + error.message)
  } finally {
    loading.value = false
  }
}

const handleDeleteCancel = () => {
  ElMessage.info('已取消删除')
}
</script>

<style scoped>
.el-descriptions {
  margin: 20px 0;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
}

:deep(.el-pagination) {
  justify-content: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
}

.el-upload {
  width: 100%;
}

.el-upload__tip {
  margin-top: 8px;
  color: #909399;
}
</style>
